package com.library.web.controller.library;

import com.library.common.annotation.Log;
import com.library.common.core.controller.BaseController;
import com.library.common.core.domain.AjaxResult;
import com.library.common.core.domain.BaseEntity;
import com.library.common.core.page.TableDataInfo;
import com.library.common.enums.BusinessType;
import com.library.common.utils.poi.ExcelUtil;
import com.library.domain.BoBook;
import com.library.domain.BoBookType;
import com.library.domain.BoBorrow;
import com.library.domain.BoMembers;
import com.library.service.IBoBookService;
import com.library.service.IBoBookTypeService;
import com.library.service.IBoBorrowService;
import com.library.service.IBoMembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 图书馆图书 信息操作处理
 *
 * @author wanghongjie
 * @date 2020-01-18
 * @blame Android Team
 */
@RestController
@RequestMapping("/library/boBook")
public class BoBookController extends BaseController {
    /**
     * 出版社、出版时间、品牌、用纸、开本、页数、编辑推荐、内容简介、书评、封面图片
     */
    /**
     * 图书管理Service类
     */
    @Autowired
    private IBoBookService boBookService;
    /**
     * 图书分类管理Service类
     */
    @Autowired
    private IBoBookTypeService boBookTypeService;
    /**
     * 图书借阅管理Service类
     */
    @Autowired
    private IBoBorrowService boBorrowService;

    /**
     * 会员管理Service类
     */
    @Autowired
    private IBoMembersService boMembersService;

    /**
     * 查询图书馆图书列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BoBook boBook) {
        startPage();
        List<BoBook> list = boBookService.selectBoBookList(boBook);
        return getDataTable(list);
    }

    /**
     * 导出图书馆图书列表
     */
    @PreAuthorize("@ss.hasPermi('library:book:export')")
    @Log(title = "图书馆图书", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BoBook boBook) {
        List<BoBook> list = boBookService.selectBoBookList(boBook);
        ExcelUtil<BoBook> util = new ExcelUtil<BoBook>(BoBook.class);
        util.exportExcel(response, list, "图书馆图书数据");
    }

    /**
     * 获取图书馆图书详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:book:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(boBookService.selectBoBookById(id));
    }

    /**
     * 新增图书馆图书
     */
    @PreAuthorize("@ss.hasPermi('system:book:add')")
    @Log(title = "图书馆图书", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BoBook boBook) {
        return toAjax(boBookService.insertBoBook(boBook));
    }

    /**
     * 修改图书馆图书
     */
    @PreAuthorize("@ss.hasPermi('system:book:edit')")
    @Log(title = "图书馆图书", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BoBook boBook) {
        return toAjax(boBookService.updateBoBook(boBook));
    }

    /**
     * 删除图书馆图书
     */
    @PreAuthorize("@ss.hasPermi('system:book:remove')")
    @Log(title = "图书馆图书", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(boBookService.deleteBoBookByIds(ids));
    }

    /**
     * 校验图书编号是否重复
     */
    @PostMapping("/checkBookNo")
    @ResponseBody
    public String checkBookNoUnique(BoBook boBook) {
        return boBookService.checkBookNoUnique(boBook);
    }

    /**
     * 获取图书分类列表
     *
     * @return
     */
    @GetMapping("/getSelectBookType")
    public AjaxResult getSelectBookType() {
        List<Map<String, String>> selected = new ArrayList<>();
        List<BoBookType> boBookTypes = boBookTypeService.selectAllBookTypeByStatus();
        boBookTypes.forEach(boBookType -> {
            Map<String, String> map = new HashMap<>();
            map.put("id", boBookType.getId().toString());
            map.put("no", boBookType.getTypeNo());
            map.put("name", boBookType.getTypeName());
            selected.add(map);
        });
        return AjaxResult.success(selected);
    }

    /**
     * 根据图书编号查询图书
     *
     * @param reqBoBook
     * @return
     */
    @GetMapping("/searchBooks")
    public AjaxResult searchBooks(BoBook reqBoBook) {
        AjaxResult ajaxResult = new AjaxResult();
        BoBook boBook = boBookService.selectBoBookByBookNo(reqBoBook.getBookNo());
        if (boBook == null) {
            return Objects.requireNonNull(ajaxResult.put("data", "图书编号[" + reqBoBook.getBookNo() + "]不存在"))
                    .put("code", 500);
        }
        BoBorrow bookBoBorrow = findBookTime(boBook.getId().longValue());
        if (bookBoBorrow != null && bookBoBorrow.getBorrowTime() != null) {
            boBook.setExt1(simpleDateFormat.format(bookBoBorrow.getBorrowTime()));
            long number = getNow().getTime() - bookBoBorrow.getBorrowTime().getTime();
            int dateNum = (int) number / (24 * 60 * 60 * 1000);
            boBook.setExt2(String.valueOf(dateNum));
        }
        return ajaxResult.put("data", boBook).put("code", 200);
    }

    private BoBorrow findBookTime(Long bookId) {
        return boBorrowService.selectBoBorrowByBookIdAndStatus(bookId);
    }

    /**
     * 图书归还操作
     *
     * @return
     */
    @GetMapping("/returnBook/{bookId}")
    public String returnBook(@PathVariable("bookId") Long bookId, ModelMap mmap) {
        BoBook book = boBookService.selectBoBookById(bookId);
        BoBorrow boBorrow = new BoBorrow();
        boBorrow.setBookId(book.getId().longValue());
        // 0 表示未归还 理论上同一本图书未归还的只要一个，一本图书不允许同一时间借给两个人
        boBorrow.setStatus(BaseEntity.STATUS_0);
        List<BoBorrow> boBorrowList = boBorrowService.selectBoBorrowList(boBorrow);
        if (boBorrowList.size() == 1) {
            BoMembers boMembers = boMembersService.selectBoMembersById(boBorrowList.get(0).getMembersId().longValue());
            mmap.put("membersName", boMembers.getMembersName());
            mmap.put("membersNo", boMembers.getMembersNo());
            mmap.put("membersPhone", boMembers.getMembersPhone());
            mmap.put("depositType", boBorrowList.get(0).getDepositType());
            mmap.put("borrowDeposit", boBorrowList.get(0).getBorrowDeposit());
        }
        mmap.put("book", book);
        return "/returnBook";
    }
}
